package com.dataaccess.dataaccess.web.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.dataaccess.dataaccess.common.base.BaseService;
import com.dataaccess.dataaccess.model.FireExtinguisherAlarmDeviceDataChanged;
import com.dataaccess.dataaccess.model.FireExtinguisherNormalDeviceDataChanged;
import com.dataaccess.dataaccess.support.model.RespEntity;
import com.dataaccess.dataaccess.support.utils.HexUtils;
import com.dataaccess.dataaccess.support.utils.MyLogger;
import com.dataaccess.dataaccess.web.mapper.FireExtinguisherAlarmDeviceDataChangedMapper;
import com.dataaccess.dataaccess.web.mapper.FireExtinguisherNormalDeviceDataChangedMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.UUID;

/**
 * 泰科灭火器
 * @author Yang yu
 * @version 1.0
 * @date 2020/8/27 17:05
 */
@Service
@Slf4j
public class DeviceAboatFireExtinguisherService extends BaseService {
    @Resource
    public MyLogger logger;
    @Resource
    private FireExtinguisherAlarmDeviceDataChangedMapper fireExtinguisherAlarmDeviceDataChangedMapper;
    @Resource
    private FireExtinguisherNormalDeviceDataChangedMapper fireExtinguisherNormalDeviceDataChangedMapper;
    @Resource
    private AsyncService asyncService;
    /**
     * 订阅--调用相关接口
     * @param
     * @return
     */
    public RespEntity getInfo(JSONObject jsonParam) {

        return RespEntity.success();
    }

    /**
     * 回调地址--设备信息变化，订阅后推送设备信息变化通知
     * @param
     * @return
     */
    public RespEntity deviceInfoChanged(JSONObject jsonParam) {

        return RespEntity.success();
    }

    /**
     * 回调地址：设备数据变化，订阅后推送设备数据变化通知
     * @param
     * @return
     */
    public RespEntity deviceDataChanged(JSONObject jsonParam) throws Exception {
        //处理支持form-data和json两种方式
        //jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        logger.info("fireExtinguisher---------"+jsonParam.toString());
        JSONObject payload = jsonParam.getJSONObject("payload");
        //设备号
        String number = "";
        //产品型号
        String productType = payload.getStr("product_type");
        //压力值
        String pressValue = payload.getStr("Press_Value");
        double vale = Double.parseDouble(pressValue) / 1000;
        //报警标志位
        String equipmentState = payload.getStr("Equipment_State");
        //报警时间
        String date = contextLoads(jsonParam.getLong("timestamp"));
        //报警标识
        boolean flag = false;
        //报警类型
        String alarmTypeName = "";
        //报警内容
        String content = "";
        //报警原始数据
        FireExtinguisherAlarmDeviceDataChanged fireExtinguisherAlarmDeviceDataChanged = new FireExtinguisherAlarmDeviceDataChanged();
        fireExtinguisherAlarmDeviceDataChanged.setId(UUID.randomUUID().toString());
        fireExtinguisherAlarmDeviceDataChanged.setJsondata(jsonParam.toString());
        fireExtinguisherAlarmDeviceDataChangedMapper.insert(fireExtinguisherAlarmDeviceDataChanged);

        //正常数据itemName
        String itemName = "";
        if (productType.equals("F")){
            String[] str = payload.getStr("device_id").split("-");
            number = str[0];
            if ("0100".equals(equipmentState)) {
                alarmTypeName = "挪用报警";
                content = "灭火器挪用";
                flag = true;
            } else if ("0010".equals(equipmentState)) {
                alarmTypeName = "灭火器报警";
                content = "压力异常 报警值:" + vale + "Mpa";
                flag = true;
            }
            itemName = "灭火器压力";
        }
        if (productType.equals("C")){
            number = jsonParam.getStr("IMEI");
            if ("0100".equals(equipmentState)) {
                alarmTypeName = "撞击报警";
                content = "撞击报警";
                flag = true;
            }else if ("0200".equals(equipmentState)) {
                alarmTypeName = "开盖报警";
                content = "开盖报警";
                flag = true;
            } else if ("0800".equals(equipmentState)) {
                alarmTypeName = "撞击传感器故障";
                content = "撞击传感器故障";
                flag = true;
            }else if ("0010".equals(equipmentState) || "0020".equals(equipmentState)) {
                alarmTypeName = "压力报警";
                content = "压力异常 报警值:" + vale + "Mpa";
                flag = true;
            }
            itemName = "水压";
        }
        JSONObject jsonParamN = new JSONObject();
        jsonParamN.put("number", number);
        if (flag) {
            jsonParamN.put("interfaceType", "1");
            jsonParamN.put("content", content);
            jsonParamN.put("alarmTypeName", alarmTypeName);
            jsonParamN.put("alarmtime", date);
            jsonParamN.put("deviceClassify", 7);
            fireFightingiot(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo");
            //异步更新设备状态
            jsonParamN.put("state","2");
            asyncService.updateDeviceCurrentState(jsonParamN);
        }else {
            //异步更新设备状态
            jsonParamN.put("state","1");
            asyncService.updateDeviceCurrentState(jsonParamN);
        }
        //正常信息
        JSONObject jSONObject = new JSONObject();
        JSONArray jSONArray = new JSONArray();
        jSONObject.put("name", itemName);
        jSONObject.put("value", vale);
        jSONArray.add(jSONObject);
        //rest调用平时数据添加接口：
        jsonParamN.put("paraminfo", jSONArray);
        jsonParamN.put("time", date);
        //return RespEntity.success(jsonParamN);
        fireFightingiot(jsonParamN, "firefightingiot_data", "normalInfo", "device");
        //平时数据
        FireExtinguisherNormalDeviceDataChanged fireExtinguisherNormalDeviceDataChanged = new FireExtinguisherNormalDeviceDataChanged();
        fireExtinguisherNormalDeviceDataChanged.setId(UUID.randomUUID().toString());
        fireExtinguisherNormalDeviceDataChanged.setJsondata(jsonParam.toString());
        fireExtinguisherNormalDeviceDataChangedMapper.insert(fireExtinguisherNormalDeviceDataChanged);
        return RespEntity.success();

    }


    /**
     * @Author YangYu
     * @Description 气体灭火系统（世成）
     * @Date Created in 09:00 2024/4/3
     * @Param [jsonParam]
     */

    public RespEntity gasFireExtinguishingData(JSONObject jsonParam) {
        //数据60600DA100010102030405100001150001A5
        String data = jsonParam.getStr("code");
        //命令字 实时数据 a1 心跳数据 a2 报警数据 a3
        String commandWord = data.substring(6,8);
        //心跳数据
        if (commandWord.equals("a2")){
            return RespEntity.success();
        }
        //网关ID
        String gatewayId = data.substring(12,22);
        //设备地址
        String number = data.substring(22,28);
        //温度
        Integer temperature = HexUtils.hexToInt(data.substring(28,30));
        // 时间
        String time = DateUtil.now();
        //设备状态 11111111
        String state = HexUtils.hexToBinaryString(data.substring(30,34));
        JSONObject jsonParamN = new JSONObject();
        jsonParamN.put("number", number);
        //报警标识
        boolean flag = false;
        if (commandWord.equals("a1")){
            if (state.charAt(7) == '0'){
                //异步更新设备状态
                jsonParamN.put("state","3");
                asyncService.updateDeviceCurrentState(jsonParamN);
                flag = true;
            }else {
                //异步更新设备状态
                jsonParamN.put("state","1");
                asyncService.updateDeviceCurrentState(jsonParamN);
            }
            if (state.charAt(6) == '1'){
                //异步更新设备状态
                jsonParamN.put("state","2");
                asyncService.updateDeviceCurrentState(jsonParamN);
                flag = true;
                jsonParamN.put("smokeState",1);
            }else {
                jsonParamN.put("smokeState",2);
            }
            if (state.charAt(5) == '1'){
                //异步更新设备状态
                jsonParamN.put("state","2");
                asyncService.updateDeviceCurrentState(jsonParamN);
                flag = true;
                jsonParamN.put("temperatureState",1);
            }else {
                jsonParamN.put("temperatureState",2);
            }
            if (state.charAt(4) == '1'){
                //异步更新设备状态
                jsonParamN.put("state","2");
                asyncService.updateDeviceCurrentState(jsonParamN);
                flag = true;
                jsonParamN.put("extinguishingDeviceState",1);
            }else {
                jsonParamN.put("extinguishingDeviceState",2);
            }
            jsonParamN.put("temperature",temperature);
            asyncService.updateGasFireExtinguishingData(jsonParamN);
        }else {
            if (state.charAt(7) == '1'){
                jsonParamN.put("interfaceType", "1");
                jsonParamN.put("content", "烟雾报警");
                jsonParamN.put("alarmTypeName", "烟雾报警");
                jsonParamN.put("alarmtime", time);
                jsonParamN.put("deviceClassify", 7);
                fireFightingiot(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo");
                //异步更新设备状态
                jsonParamN.put("state","2");
                asyncService.updateDeviceCurrentState(jsonParamN);
                flag = true;
            }
            if (state.charAt(6) == '1'){
                jsonParamN.put("interfaceType", "1");
                jsonParamN.put("content", "温度报警 值："+temperature+"°C");
                jsonParamN.put("alarmTypeName", "温度报警");
                jsonParamN.put("alarmtime", time);
                jsonParamN.put("deviceClassify", 7);
                fireFightingiot(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo");
                //异步更新设备状态
                jsonParamN.put("state","2");
                asyncService.updateDeviceCurrentState(jsonParamN);
                flag = true;
            }
            if (state.charAt(5) == '1'){
                jsonParamN.put("interfaceType", "1");
                jsonParamN.put("content", "灭火装置已喷发");
                jsonParamN.put("alarmTypeName", "系统事件");
                jsonParamN.put("alarmtime", time);
                jsonParamN.put("deviceClassify", 7);
                fireFightingiot(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo");
                //异步更新设备状态
                jsonParamN.put("state","2");
                asyncService.updateDeviceCurrentState(jsonParamN);
                flag = true;
            }
        }
        return RespEntity.success();
    }

    /**
     * @Author YangYu
     * @Description 气体灭火系统（京电云）
     * @Date Created in 09:00 2024/4/3
     * @Param [jsonParam]
     */

    public RespEntity gasFireExtinguishingIotData(JSONObject jsonParam) {
        try {
            //原始数据
            JSONObject payload = jsonParam.getJSONObject("payload");

            //网关ID
            String gatewayId = payload.getJSONObject("gwDeviceBo").getStr("serialNumber");
            //设备ID
            String serialNumber = payload.getStr("serialNumber");
            //模型数据
            JSONArray jsonArray = payload.getJSONArray("thingsModelSimpleItem");
            //报警标识
            boolean alarmFlag = false;
            //设备状态报警、故障状态 11111111
            String alarmStatus = "";
            //设备状态报警、故障状态 11111111
            String deviceStatus = "";
            //温度
            Integer temperature = 0;
            //报警类型
            String alarmType = "";
            //烟雾状态
            Integer smokeState = 0;
            //灭火装置状态
            Integer deviceState = 0;
            //温度状态
            Integer temperatureStatus = 0;
            for (Object obj : jsonArray) {
                JSONObject jsonObject = (JSONObject) obj;
                if (jsonObject.getStr("id").equals("smoke_state")){
                    if (jsonObject.getStr("value").equals("1")){
                        smokeState = 1;
                    }
                }
                if (jsonObject.getStr("id").equals("device_state")){
                    if (jsonObject.getStr("value").equals("1")){
                        deviceState = 1;
                    }
                }
                if (jsonObject.getStr("id").equals("temperature_status")){
                    if (jsonObject.getStr("value").equals("1")){
                        temperatureStatus = 1;
                    }
                }
                if (jsonObject.getStr("id").equals("temperature")){
                    temperature = jsonObject.getInt("value");
                }
            }
            // 时间
            String time = DateUtil.now();
            //组装数据
            JSONObject jsonParamN = new JSONObject();
            jsonParamN.put("number", gatewayId + serialNumber);

            if (smokeState == 1){
                jsonParamN.put("interfaceType", "1");
                jsonParamN.put("content", "烟雾报警");
                jsonParamN.put("alarmTypeName", "烟雾报警");
                jsonParamN.put("alarmtime", time);
                jsonParamN.put("deviceClassify", 7);
                fireFightingiot(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo");
                //异步更新设备状态
                jsonParamN.put("state","2");
                asyncService.updateDeviceCurrentState(jsonParamN);
                jsonParamN.put("smokeState",1);
                alarmFlag = true;
            }else {
                jsonParamN.put("smokeState",2);
            }
            if (deviceState == 1){
                jsonParamN.put("interfaceType", "1");
                jsonParamN.put("content", "灭火装置已喷发");
                jsonParamN.put("alarmTypeName", "系统事件");
                jsonParamN.put("alarmtime", time);
                jsonParamN.put("deviceClassify", 7);
                fireFightingiot(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo");
                //异步更新设备状态
                jsonParamN.put("state","2");
                asyncService.updateDeviceCurrentState(jsonParamN);
                jsonParamN.put("extinguishingDeviceState",1);
                alarmFlag = true;
            }else {
                jsonParamN.put("extinguishingDeviceState",2);
            }
            if (temperatureStatus == 1){
                jsonParamN.put("interfaceType", "1");
                jsonParamN.put("content", "温度报警 值："+temperature+"°C");
                jsonParamN.put("alarmTypeName", "温度报警");
                jsonParamN.put("alarmtime", time);
                jsonParamN.put("deviceClassify", 7);
                fireFightingiot(jsonParamN, "communication", "notificationAlarmHandel", "alarmInfo");
                //异步更新设备状态
                jsonParamN.put("state","2");
                asyncService.updateDeviceCurrentState(jsonParamN);
                jsonParamN.put("temperatureState",1);
                alarmFlag = true;
            }else {
                jsonParamN.put("temperatureState",2);
            }
            jsonParamN.put("temperature",temperature);
            asyncService.updateGasFireExtinguishingData(jsonParamN);
            if (!alarmFlag){
                jsonParamN.put("state","1");
                asyncService.updateDeviceCurrentState(jsonParamN);
            }
            JSONObject jsonObject = new JSONObject();
            if (alarmFlag){
                jsonObject.put("number", gatewayId);
                jsonObject.put("state","2");
                asyncService.updateDeviceCurrentState(jsonObject);
            }else {
                jsonObject.put("number", gatewayId);
                jsonObject.put("state","1");
                asyncService.updateDeviceCurrentState(jsonObject);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return RespEntity.success();
    }

    /**
     * 将毫秒转化为日期(格式:yyyy-MM-dd hh:mm:ss)
     * @param l
     * @return
     * @throws Exception
     */
    public String contextLoads(Long l) throws Exception {

        java.text.SimpleDateFormat sdf1=new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
        Date date = new Date(l);
        String str1 = sdf1.format(date);
        java.text.SimpleDateFormat sdf=new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date2 = sdf.parse(str1);
        String str2 = sdf.format(date2);
        return str2;
    }

    public static void main(String[] args) {
        //处理支持form-data和json两种方式
        //jsonParam = HttpRequestUtil.commonHttpRequestParamConvert(getRequest());
        String mes = "{\"upPacketSN\":-1,\"deviceType\":\"\",\"productId\":\"10093266\",\"IMEI\":\"864162042124969\",\"deviceId\":\"9afbbae38a7f45058f315fe675a3f45d\",\"protocol\":\"lwm2m\",\"messageType\":\"dataReport\",\"payload\":{\"temperature\":15,\"sinr\":-125,\"rsrp\":-823,\"product_type\":\"F\",\"pressure_units\":3,\"pci\":129,\"ecl\":2,\"device_id\":\"04A32710-864162042124969\",\"cell_id\":229936724,\"battery_value\":96,\"Voltage\":37,\"Version\":\"0501\",\"Press_Value\":1180,\"General_data\":\"0000\",\"Equipment_State\":\"0100\",\"CSQ\":26},\"assocAssetId\":\"\",\"tenantId\":\"2000000077\",\"IMSI\":\"undefined\",\"topic\":\"v1/up/ad19\",\"upDataSN\":-1,\"serviceId\":4,\"timestamp\":1606117939761}";
        JSONObject jsonParam = JSONUtil.parseObj(mes);
        JSONObject payload = jsonParam.getJSONObject("payload");
        //设备号
        String[] str = payload.getStr("device_id").split("-");
        String number = str[0];
        //产品型号
        String productType = payload.getStr("product_type");
        //压力值
        String pressValue = payload.getStr("Press_Value");
        double vale = Double.parseDouble(pressValue) / 1000;
        //报警标志位
        String equipmentState = payload.getStr("Equipment_State");
        //报警时间
        String date = "";
        //报警标识
        boolean flag = false;
        //报警类型
        String alarmTypeName = "";
        //报警内容
        String content = "";
        if ("0100".equals(equipmentState)) {
            alarmTypeName = "挪用报警";
            content = "灭火器晃动";
            flag = true;
        } else if ("0010".equals(equipmentState)) {
            alarmTypeName = "灭火器报警";
            content = "压力异常 报警值:" + vale + "Mpa";
            flag = true;
        }
        JSONObject jsonParamN = new JSONObject();
        jsonParamN.put("number", number);
        if (flag == true) {
            jsonParamN.put("interfaceType", "1");
            jsonParamN.put("content", content);
            jsonParamN.put("alarmTypeName", alarmTypeName);
            jsonParamN.put("alarmtime", date);
            jsonParamN.put("deviceClassify", 7);
        }
        //正常信息
        JSONObject jSONObject = new JSONObject();
        JSONArray jSONArray = new JSONArray();
        jSONObject.put("name", "灭火器压力");
        jSONObject.put("value", vale);
        jSONArray.add(jSONObject);
        //rest调用平时数据添加接口：
        jsonParamN.put("paraminfo", jSONArray);
        jsonParamN.put("time", date);
        //return RespEntity.success(jsonParamN);
    }
}
